package com.service.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.service.acl.pojo.Permission;
import com.service.acl.mapper.PermissionMapper;
import com.service.acl.pojo.RolePermission;
import com.service.acl.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.service.acl.service.RolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 权限 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-10-22
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private RolePermissionService rolePermissionService;


    @Override
    public List<Permission> queryAll() {
        return queryChildren("0");
    }

    @Override
    public List<Permission> queryChildren(String pid) {
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.eq("pid",pid);
        List<Permission> permissions = this.list(permissionQueryWrapper);
        for (Permission permission : permissions) {
            List<Permission> permissionList = queryChildren(permission.getId());
            if (permissionList!=null){
                permission.setChildren(queryChildren(permission.getId()));
            }
        }
        return permissions;
    }

    @Override
    public List<Permission> queryRoleId(String roleId) {
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        List<RolePermission> list = rolePermissionService.list(queryWrapper);
        List<Permission> permissions = new ArrayList<>();
        for (RolePermission rolePermission : list) {
            Permission permission = this.getById(rolePermission.getPermissionId());
            permission.setChildren(queryChildren(permission.getId()));
            permissions.add(permission);
        }
        return permissions;
    }

    @Override
    public void delete(String id) {
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq("permission_id",id);
        rolePermissionService.remove(rolePermissionQueryWrapper);
        this.removeById(id);
    }
}
